package com.free.semantic.core.funcimpl;

import com.free.semantic.core.Context;

import java.util.ArrayList;
import java.util.List;

public class MultipleKeyFuncImpl extends BaseFuncImpl {

    private String[] source;

    private String dest;

    private MultipleKeyMap keyResMap;

    public MultipleKeyFuncImpl(String[] source, String dest, MultipleKeyMap keyResMap) {
        this.source = source;
        this.dest = dest;
        this.keyResMap = keyResMap;
        assert source.length == keyResMap.getKeyLength();
    }

    private static List<List<String>> multi(List<List<String>> allKeyLs, List<String> keyLs) {
        List<List<String>> result = new ArrayList<>();
        for (String key : keyLs) {
            if (allKeyLs.size() == 0) {
                List<String> line = new ArrayList<>();
                line.add(key);
                result.add(line);
            } else {
                for (List<String> allKey : allKeyLs) {
                    List<String> line = new ArrayList<>(allKey);
                    line.add(key);
                    result.add(line);
                }
            }
        }
        return result;
    }

    @Override
    public void calculate(Context context) {
        List<String> result = new ArrayList<>();
        List<List<String>> listValue = new ArrayList<>();
        for (String sourceKey : source) {
            listValue.add(context.getListValue(sourceKey));
        }
        List<List<String>> allKeyLs = new ArrayList<>();
        for (int i = 0; i < listValue.size(); i++) {
            List<String> keyLs = listValue.get(i);
            allKeyLs = multi(allKeyLs, keyLs);
        }
        for (List<String> allKeyL : allKeyLs) {
            result.add(keyResMap.get(allKeyL));
        }
        context.setValue(dest, result);
    }

    public String[] getSource() {
        return source;
    }

    public void setSource(String[] source) {
        this.source = source;
    }

    public String getDest() {
        return dest;
    }

    public void setDest(String dest) {
        this.dest = dest;
    }

    public MultipleKeyMap getKeyResMap() {
        return keyResMap;
    }

    public void setKeyResMap(MultipleKeyMap keyResMap) {
        this.keyResMap = keyResMap;
    }


}
